package org.pub.fast.jdbc.cross.adapter;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.pub.fast.jdbc.cross.CrossDBPreparedStatement;
import org.pub.fast.jdbc.util.DBUtil;

public class PostgresAdapter extends BaseAdapter {
	public String getName() {
		return getClass().getName();
	}

	public String getDriverClass() {
		return "org.postgresql.Driver";
	}

	public Object getObject(ResultSet rs, int columnIndex, int scale)
			throws SQLException {
		return convert(rs.getObject(columnIndex), scale);
	}

	public Object getObject(ResultSet rs, String columnName, int scale)
			throws SQLException {
		return convert(rs.getObject(columnName), scale);
	}

	private static Object convert(Object value, int scale) {
		if (value instanceof Short) {
			return Integer.valueOf(String.valueOf(value));
		} else if (value instanceof BigDecimal) {
			if (value instanceof java.math.BigDecimal && scale <= 0) {
				if (DBUtil.needToInt((BigDecimal) value)) {
					value = new Integer(((BigDecimal) value).intValue());
				}
			}
			return value;
		} else if (value instanceof Long) {
			Long l = Math.abs(((Long) value));
			if (l.compareTo(new Long(Integer.MAX_VALUE)) < 0) {
				return ((Long) value).intValue();
			}
		}
		return value;
	}

	public boolean getBoolean(ResultSet rs, String columnName)
			throws SQLException {
		return rs.getBoolean(columnName);
	}

	public boolean getBoolean(ResultSet rs, int columnIndex)
			throws SQLException {
		return rs.getBoolean(columnIndex);
	}

	public void setBoolean(CrossDBPreparedStatement prep, int parameterIndex,
			boolean v) throws SQLException {
		((PreparedStatement) prep.getVendorObject()).setString(parameterIndex, v ? "Y" : "N");
	}

}
